import Vue from 'vue'
import VueRouter from 'vue-router'
// import HomeView from '../views/HomeView.vue'
import LoginView from '@/views/LoginView.vue'
import WecomeView from '@/views/WecomeView.vue'
import HomeView from '@/views/HomeView.vue'
import UserView from '@/views/user/UserView.vue'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: WecomeView },
      { path: '/users', component: UserView }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 挂载全局导航守卫
router.beforeEach((to, from, next) => {
  if (to === from) {
    next()
    return
  }
  // from从哪里来，to去哪里，next函数跳转
  // 只要不是登录页，都要查看token
  if (to.path === '/login') {
    next()
  } else {
    // 读取token
    const token = window.localStorage.getItem('token')
    if (!token) {
      next('/login')
    } else {
      next()
    }
  }
})
export default router
